/*
 * Copyright 2020-2025 the original author or authors.
 * You cannot use this file unless authorized by the author.
 */
package org.ipig.model.store;

import org.ipig.constants.SymbolCnst;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.ToString;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * RecordRowKey
 *
 * @author <a href="mailto:comchnts@163.com">chinats</a>
 * @version $$Id: RecordRowKey.java 3 2020-01-21 09:36:33Z ts <comchnts@163.com> $$
 * @since 1.0
 */
@Data
@ToString
public class RecordRowKey implements Serializable {
    /**
     * 库名
     **/
    private String schema;
    /**
     * 表名
     **/
    private String table;
    /**
     * 主键KV
     **/
    private Map<String, String> primaryKeyValues = new LinkedHashMap<String, String>();

    /**
     * 构建记录RowKey
     *
     * @param schema
     * @param tableName
     * @param primaryKeys
     * @param afterData
     * @return
     */
    private RecordRowKey buildRecordRowKey(String schema, String tableName, String[] primaryKeys, JSONObject afterData) {
        RecordRowKey rowKey = new RecordRowKey();
        rowKey.setSchema(schema);
        rowKey.setTable(tableName);
        for (int i = 0; i < primaryKeys.length; i++) {
            rowKey.getPrimaryKeyValues().put(primaryKeys[i], StringUtils.trimToEmpty(String.valueOf(afterData.get(primaryKeys[i]))));
        }
        return rowKey;
    }

    public String getRowKey() {
        StringBuilder sb = new StringBuilder(schema).append(SymbolCnst.DOT).append(table).append(SymbolCnst.AT);
        for (Map.Entry<String, String> entry : primaryKeyValues.entrySet()) {
            sb.append(SymbolCnst.MIDLINE).append(entry.getValue());
        }
        return sb.toString();
    }
}
